﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using WAF.DAO;
using WAF.EntityFramework;

namespace EntityTools.Model
{
    public partial class TableInfo
    {
        public static TableInfo[] GetTableList(string databaseID)
        {
            string sql = "SELECT Id, TableName FROM TableInfo WHERE DatabaseID=" + databaseID;

            TableInfo[] tbInfos = EntityAction.Select<TableInfo>(sql);

            return tbInfos;
        }

        public static string AddTableInfo(long databaseID, string tableName, out TableInfo tbInfo)
        {
            string result = null;
            tbInfo = null;
            TableInfo tb = new TableInfo() { DatabaseID = databaseID, TableName = tableName };

            string sql = "select count(*) from TableInfo where DatabaseID=@dbID and TableName=@tbName";
            DbParameters parms = new DbParameters();
            parms.Add("dbID", tb.DatabaseID, DbType.Int64);
            parms.Add("tbName", tb.TableName, DbType.String);
            int count = int.Parse(DbAccess.ExeScalar(sql, parms).ToString());

            if (count != 0)
                result = "在该数据库中此表名已经存在！";
            else
            {
                long id = EntityAction.Insert(tb);
                tb.Id = id;
                tbInfo = tb;
            }

            return result;
        }

        /// <summary>
        /// 删除该表的所有信息（包括该表的字段信息）
        /// </summary>
        /// <param name="tableID"></param>
        public static void DeleteTableInfo(long tableID)
        {
            DbAccess dbAccess = new DbAccess();

            try
            {
                dbAccess.Open();
                dbAccess.BeginTransaction();

                //删除该表的字段信息
                dbAccess.ExecuteNonQuery("DELETE FROM FieldInfo WHERE TableID=" + tableID.ToString());

                //删除该表
                dbAccess.ExecuteNonQuery("DELETE FROM TableInfo WHERE Id=" + tableID.ToString());

                dbAccess.CommitTtransaction();
            }
            catch (Exception ex)
            {
                dbAccess.RollbackTtransaction();
                throw ex;
            }
            finally
            {
                dbAccess.Close();
            }
        }
    }
}
